 19 - File Input and Output in C# 18 - Delegates and Events in C#20 - Exception Handling in C# 19.1 Implementing the File Input and Output OperationsPrograms accept input from the user, process the input and produces an output. All the languages support input and output operations. The file is a collection of data stored on a disk with the specific name and directory path. The file open for reading and writing data is known as stream.The stream is a sequence of bytes from source to destination through the communication path. The two basic streams are the input and output streams. Every stream has a function associated with it. The input stream is used for read operation and output stream is used for a write operation.The System.IO namespace contains various classes, used for performing operations as file creation, file deletion, read – write operations.The following table is used to describe the classes in the System.IO namespace.Class NameDescriptionFileStreamIt is used to read and write from any location within a fileBinaryReaderIt is used to read primitive data types from a binary streamBinaryWriterIt is used to write primitive data types in a binary format to a binary streamStreamReaderIt is used to read characters from a byte streamStreamWriterIt is used to write characters to a streamStringReaderIt is used to read from a string bufferStringWriterIt is used to write into a string bufferDirectoryInfoIt is used to perform operations on directionsFileInfoIt is used to perform operations on filesFileStream ClassThe file input/output operations is implemented in the System.IO namespace. User can use the FileStream class in the System.IO namespace to read, write, and close files. These classes are inherited from an abstract class called Stream.The following syntax is used to create an object of the FileStream class:          FileStream <objectname> = new FileStream ( <file name>, <file Mode Enumerator>,                                                         <File Access Enumerator> , <FileShare Enumerator> ); The code snippet for creating an object of the FileStream class is as shown below:          FileStream fs = new FileStream ( “data.txt”, FileMode.Open. FileAccess.Read, FileShare.Read);  In the code snippet, the FileMode, FileAccess and FileShare enumerators define constants used by the FileStream class.FileMode EnumeratorThe FileMode Enumerator defines methods for opening files. It is used to restrict the mode in which the file is opened by the user. The parameters to the enumerator check if the file is overwritten created or opened.The members of the enumerator are as follows:1) Append: It opens the file if it exists and places the cursor at the end of the file or creates a new file.2) Create: It creates a new file3) CreateNew: It specifies to an operating system that a new file should be created4) Open: It opens an existing file5) OpenOrCreate: It specifies to the system that open a file if it exists, else create a new file6) Truncate: It opens an existing file. When opened, the file should be truncated, the size of the file is zero bytesFile Access EnumeratorThe file is opened for both reading and writing operations. The enumerator is used to indicate whether user wants to read data from a file, write data to the file or perform both operations.The members of the enumerator are Read, Write and ReadWrite.FileShare EnumeratorThe enumerator contains constants for controlling the access that the FileStream constructors have on the file. The use of the enumeration is to define whether two different applications can simultaneously read from the same file.The members of the FileShare enumerator are as follows:1) Inheritable: It allows a file handle to pass the inheritance to the child processes2) None: It rejects sharing of the current file3) Read: It allows the opening of a file for reading purpose4) ReadWrite: It allows opening a file for the purpose of reading and writing5) Write: It allows the opening of a file for writing19.2 Implementing Reading and Writing in the Text FilesThe Stream class is used to read data and write data to the text files. The StreamReader and StreamWriter class are used to read and write data in the files.StreamReader ClassThe StreamReader class is inherited from the abstract class as TextReader. The class represents a reader used for reading a series of characters.The following table is used to represent the methods used in the StreamReader classMethodsDescriptionCloseIt closes the object of the StreamReader class and stream, and releases system resources associated with the readerPeekIt returns the next available character but does not consume itReadIt reads the next character or the next set of characters from the streamReadLineIt reads a line of characters from the current stream and returns data as a stringSeekIt allows the read/write position to be moved to any position within the fileThe following code is used to implement the StreamReader class to read data from a file
class Program
{
    public void ReadData()
    {
        FileStream fs = new FileStream("E:\\data.txt", FileMode.Open, FileAcess.Read);
        StreamReader sr = newStreamReader ( fs );
        sr.BaseStream.Seek( 0, SeekOrigin.Begin);
        string str = sr.ReadLine();
        while ( str ! = null )
        {
            Console.WriteLine("{0}", str );
            str = sr.ReadLine();
        }
            sr.Close();
            fr.Close();
    }
    static void Main ( string[ ] args )
    {
        Program p = new Program();
        p.ReadData();
        Console.Read();
    }
}

The output for the code is as shown below:In the above code, the FileMode property value is used to Open and FileAccess property value is Read. The file data.txt is in open mode and prepares the stream for read operation. The reader statement creates a new instance of the StreamReader class for the text file.The Seek() method allows the read position to be moved to the beginning of the file and read till the end of the file.StreamWriter ClassThe StreamWriter class is inherited from the abstract class called TextWriter. The class represents a writer, which can write a series of characters.The following table describes the methods of the StreamWriter class.MethodsDescriptionCloseIt closes the current object and the streamFlushIt clears all buffers for the current writer and causes any buffered data to be written to the streamWriteIt writes to the streamWriteLineIT writes data specified by the overloaded parameters, followed by the end of lineThe following code implements the StreamWriter class to accept data from the user and write it into the file.
class Program
{
    public void WriteData()
    {
        FileStream fs = new FileStream(“E://data.txt”, FileMode.Append, FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);
        Console.WriteLine(“Enter the string”)l
        string str = Console.ReadLine();
        w.Write(str);
        w.Flush();
        fs.Close();
    
    }
    static void Main ( string[ ] args )
    {
        Program p = new Program();
        p.WriteData();
        Console.Read();
    }
}

The output for the code is as shown below:The text file name data contains the string. The file is as shown below:In the above code, The FileMode property value is Append and the FileAccess property value is Write. The file data.txt is opened in the append mode and the stream is used for the write operation. A new instance of the StreamWriter class is created.The Flush() method clears the stream buffer. The Close() method closes the stream and releases the resources associated with the stream.19.3 Implementing Reading and Writing in Binary FilesThe information stored in the text format would be displayed on the screen as text. Reading an:d writing data in the binary format means the number is written as float consuming four bytes of space. The BinaryReader and BinaryWriter classes are used for reading and writing binary data in files.BinaryReader ClassThe BinaryReader class is used to read binary data from a file. The BinaryReader object is passed to the FileStream object to the constructor. The code snippet is as shown below:The following table shows the methods of the BinaryReader class.MethodDescriptionCloseIt closes the current reader and streamReadIt reads the characters from the stream and moves to the current position of the streamBinaryWriter ClassThe BinaryWriter class is used to write binary data to a stream. User can create BinaryWriter object by passing the FileStream object to the constructor.The following table shows the methods used by the BinaryWriter class.MethodDescriptionCloseIt closes the current BinaryWriter object and streamSeekIt sets the position within the current streamWriteIt writes the value to the current streamFlushIt clears the buffer for the current writer and the buffered data is written to the deviceThe following code is used for implementing the BinaryReader and BinaryWriter classes to read and write data to the files.
class Program
{
    static void Main ( string[ ] args )
    {
        BinaryReader datain;
        BinaryWriter dataout;

        int i=20;
        double j = 101.50;
        bool b = true;

        dataout = new BinaryWriter( new FileStream ( “data”, FielMode.Create ) );
        Console.WriteLine(“Writing is”+ i );
        dataout.Write ( i );

        Console.WriteLine(“Writing is”+ j);
        dataout.Write ( j );  

        Console.WriteLine(“Writing is”+ b );
        dataout.Write ( b );

        Console.WriteLine( “Writing” + 12.2 * 15.5 );
        dataout. Write( 12.2 * 15.5 );

        dataout.Close();
        Console.WriteLine();

        datain = new BinaryReader ( new FileStream ( “data”, FileMode.Open ) );
        i = datain.ReadInt32();
        Console.WriteLine( “Reading” + i );
 
        j = datain.ReadDouble();
        Console.WriteLine( “Reading” + j );

        b = datain.ReadBoolean();
        Console.WriteLine( “Reading” + b );

        j = datain.ReadDouble();
        Console.WriteLine( “Reading” + j );

        Console.Read();
        datain.Close();
    }
}

 The output for the code is as shown below:19.4 Implementing the Windows File SystemIt is necessary for the user to locate the files and directories. The FileInfo and DirectoryInfo classes are used for gathering information about files and directories at the specified location.DirectoryInfo ClassThe DirectoryInfo class is derived from the FileSystemInfo class. The following table shows some of the properties of the DirectoryInfo class.PropertyDescriptionAttributesIt gets or sets attributes of the current file. It is an inherited property from FileSystemInfo class.CreationTimeIt gets or sets the creation time of the file.ExistsIt gets a Boolean value indicating whether the directory exists or not.ExtensionIt gets a string containing the file extension.FullNameIt gets a string containing full path of the directory.LastAccessTimeIt gets the last accessed time of the directory.NameIt gets a string containing the name of a given file.The following table describes the commonly used methods of the DirectoryInfo class.MethodDescriptionCreateIt creates a directory.CreateSubDirectoryIt creates a subdirectory.DeleteIt deleted a directory.GetDirectoriesIt returns the directories in the current directory after all the criteria are matched.GetFilesIt returns the files in the current directory.The code snippet for creating the DirectoryInfo object is as shown below:
class Program
{
    static void Main ( string[ ] args )
    {
        DirectoryInfo dirinfo = new DirectoryInfo ( @”C:\\Windows”);
        Console.WriteLine(“Full Name of the directory is : {0}”, dirinfo.FullName );
        Console.WriteLine(“The directory was last accesses on: {0}”, dirinfo.LastAccessTime.ToString() );
        Console.Read();    
    }
}

The output for the code is as shown below:In the above snippet, the object of DirectoryInfo is created. It displays the full name and last time when it was accessed.FileInfo ClassThe FileInfo class is derived from the FileSystemInfo class. The following table contains the properties of the FileInfo class.PropertyDescriptionAttributesIt gets or sets the attributes associated with the current file.CreationTimeIt gets or sets the creation time of the current file.DirectoryIt gets an instance of the directory to which it belongs.ExistsIt gets a Boolean value indicating whether a file exists or not.ExtensionIt gets a string containing file extension.FullNameIt gets a string containing full path of the file.LastAccessTimeIt gets the last accessed time of the file.LastWriteTimeIt gets the time of last written activity to the file.LengthIt gets the size of the file.NameIt gets a string containing the name of a given file.The following table shows the methods of the FileInfo class.MethodDescriptionCreateIt creates a file.AppendTextIt appends a text to the file represented by the FileInfo object.DeleteIt deletes a fileOpenIt opens file.OpenReadIt opens a file in read – only mode.The code snippet demonstrating the FileInfo class is a shown below:
class Program
{
    static void Main ( string[ ] args )
    {
        DirectoryInfo dirinfo = new DirectoryInfo ( @”C:\\Windows”);
        FileInfo[ ] FileInDir = dirinfo.GetFiles();
        foreach ( FileInfo file in FileDir )
        {
            Console.WriteLine(“File Name {0} Size: {1} bytes”, filename, file.Length );
        }
        Console.Read();
    }
}

The output for the code is as shown below:In the above code, the GetFiles() method is used to retrieve the list of all the files in the directory. It displays the list of all the files in the directory along with their sizes. 18 - Delegates and Events in C#20 - Exception Handling in C# 


Wideskills




